#!/usr/bin/env python
# Create: 2019/4/18
__author__ = '749B'
"""根据端口id号删除端口
删除之前会先做检查，理论上保证不会误删
"""

import requests

from sds.swis_login import swis


def get_info_by_id(iid):
    """第一步：
    通过id查找端口信息
    """
    results = swis.query("SELECT InterfaceID, StatusDescription, Uri "
                         "FROM Orion.NPM.Interfaces "
                         "WHERE InterfaceID = @id",
                         id=iid)
    if len(results['results']) > 1:
        print("找到多条以上的记录: %s %d" % ('Orion.NPM.Interfaces', iid))
        return
    if len(results['results']) != 1:
        print("未找到任何记录: %s %d" % ('Orion.NPM.Interfaces', iid))
        return
    if not check_results(results['results'][0]):
        return
    # 检查完成，删除端口
    print("Deleting: {}".format(results['results'][0]['InterfaceID']), end="...")
    swis.delete(results['results'][0]['Uri'])
    print("DONE")


def check_results(res_dic):
    """第二步：
    检查端口状态
    """
    if res_dic['StatusDescription'] not in ['Down', 'Unmanaged', 'Unknown']:
        print("设备状态不对: %s %s" % (res_dic['InterfaceID'], res_dic['StatusDescription']))
        return False
    return check_downtime_by_id(res_dic['InterfaceID'])


def check_downtime_by_id(iid):
    """第三步：
    查找并检查端口状态的持续时间
    """
    results = swis.query("SELECT TotalDurationMin "
                         "FROM Orion.NPM.InterfaceNetObjectDowntime "
                         "WHERE EntityId = @id AND EntityType = 'Orion.NPM.Interfaces' ",
                         id=iid)
    if len(results['results']) > 1:
        print("找到多条以上的记录: %s %d" % ('Orion.NPM.InterfaceNetObjectDowntime', iid))
        return
    if len(results['results']) != 1:
        print("未找到任何记录: %s %d" % ('Orion.NPM.InterfaceNetObjectDowntime', iid))
        return
    if results['results'][0]['TotalDurationMin'] < TOTAL_DURATION_IN_MINUTES:
        print("中断时间异常: %d < %d" % (results['results'][0]['TotalDurationMin'], TOTAL_DURATION_IN_MINUTES))
        return False
    return True


requests.packages.urllib3.disable_warnings()
TOTAL_DURATION_IN_MINUTES = 518400  # 300天是518400

if __name__ == '__main__':
    get_info_by_id(28971)



